<?php

namespace app\store\service;
use think\facade\Db;

class RoleService
{   

    protected $store_id;

    protected $admin_id;
    
    public function __construct()
    {
        $this->store_id = session('store_id');
        $this->admin_id = session('user_id');
    }

    public function getRoleList($keyword)
    {   
        $query = Db::name('role')->where('store_id',$this->store_id)->field('id,name,remark,status,create_time,update_time');

        if(!empty($keyword)){
            $query->whereLike('name',"%$keyword%");
        }

        $roles = $query->paginate();
        
        return $roles;
    }

    public function findRoleDetail($id)
    {
        $role = Db::name('role')->withOutField('create_time,update_time')->find($id);

        return $role;
    }

    public function getMenuTree($role_id)
    {   
        $ids = Db::name('role_menu')->alias('a')->join('menu b','a.menu_id=b.id')->field('a.menu_id')->where('a.role_id',$role_id)->where('b.parent_id','>',0)->select(); 
        
        $adminService = new AdminService();

        $menus = $adminService->getMenuList($this->admin_id);
        
        $idArr = $ids->isEmpty() ? [] : array_column($ids->toArray(),'menu_id');
        
        $data = $this->generateTree($menus);
        
        return ['idArr' => $idArr,'data' => $data];
    }

    public function generateTree($arr = array())
    {
            $items = array();
            foreach ($arr as $value) {
                $value['spread'] = true;
                $items[$value['id']] = $value;
            }
            
            $tree = array();
            foreach ($items as $key => $item) {
                if (isset($items[$item['parent_id']])) {
                    $items[$item['parent_id']]['children'][] = &$items[$key];
                } else {
                    $tree[] = &$items[$key];
                }
            }
            return $tree;
     
    }


    public function savePermission($role_id,$param)
    {   
        Db::startTrans();
        try {
            Db::name('role_menu')->where('role_id',$role_id)->delete();  
            Db::name('role_menu')->insertAll($param);
            // 提交事务
            Db::commit();

            return true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();

            return false;
        }
    }

  
    
}